<template>
  <div v-loading="loading" class="listedDealForm" :style="{ background: (currentPage === 'spo' ? 'white' : ''), padding: (currentPage === 'spo' ? '10px': '0')}">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <deal-select
              v-model="form.dealId"
              :disabled="form.id !== undefined || currentPage === 'spo'"
              scope="true"
              :deal-status="($route.query.dealStatus === undefined ? 'TH' : $route.query.dealStatus)"
              :deal-type="($route.query.dealType === undefined ? 'equity' : $route.query.dealType)"
              :placeholder="$t('请选择项目')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('市场')" prop="market">
            <dict-select
              v-model="form.market"
              dictionary="listed_market"
              :placeholder="$t('市场')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证券代码')" prop="stockCode">
            <el-input v-model="form.stockCode" :placeholder="$t('证券代码')">
              <template slot="append" icon="el-icon-search">
                <el-button
                  v-hasPermi="['listed:base:edit']"
                  type="primary"
                  icon=""
                  size="mini"
                  @click="getClosePrice(form.stockCode)"
                >{{ $t('查询股票详情') }}</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最新收盘价(元/股)')" prop="closePrice">
            <Money v-model="form.closePrice" :placeholder="$t('最新收盘价(元/股)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('市值') + $t('金额单位')" prop="marketValue">
            <span slot="label">
              {{ $t('市值') + $t('金额单位') }}
              <el-tooltip :content="$t('(市值=最新收盘价x我方持有股数)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.marketValue" unit="w" :placeholder="$t('市值') + $t('金额单位')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上市日期')" prop="launchDate">
            <el-date-picker
              v-model="form.launchDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('上市日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('负责人')" prop="personCharge">
            <UserSelect v-model="form.personCharge" :placeholder="$t('负责人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总股本(万股)')" prop="totalEquity">
            <Money v-model="form.totalEquity" :placeholder="$t('总股本(万股)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总流通股(万股)')" prop="currCapital">
            <Money v-model="form.currCapital" :placeholder="$t('总流通股(万股)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否存在董监高')" prop="whetherBod">
            <el-select v-model="form.whetherBod" value="" clearable :placeholder="$t('是否存在董监高')">
              <el-option
                v-for="dict in yesNoOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.whetherBod === 'Y'" :span="12">
          <el-form-item :label="$t('董监高人员')" prop="bodList">
            <el-input v-model="form.bodList" :placeholder="$t('董监高人员')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="shareHold">
            <span slot="label">
              {{ $t('我方持有股数(万股)') }}
              <el-tooltip :content="$t('(我方持有股数=项目【持仓信息】模块中所有的持仓股数之和)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.shareHold" disabled :placeholder="$t('我方持有股数(万股)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="shareRate">
            <span slot="label">
              {{ $t('持股比例(%)') }}
              <el-tooltip :content="$t('(持股比例=我方持有股数/总股本)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Ratio v-model="form.shareRate" disabled :placeholder="$t('持股比例(%)')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('我方投资总金额') + $t('金额单位')" prop="totalInvestAmount">
            <span slot="label">
              {{ $t('我方投资总金额') + $t('金额单位') }}
              <el-tooltip :content="$t('(我方投资总金额=项目【持仓信息】模块中所有的投资成本之和)')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.totalInvestAmount" unit="w" disabled :placeholder="$t('我方投资总金额') + $t('金额单位')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--证券账户持仓信息-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('证券账户持仓信息') }}</span>
      </div>
      <el-table :data="form.listedPositionHoldList" border class="nowrapTable formTable" row-class-name="cellClass">
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('证券账号')" align="center" show-overflow-tooltip min-width="280">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('证券账号') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedPositionHoldList.' + scope.$index + '.securityId'" :rules="listedPositionHoldListRules.securityId">
              <el-select v-model="scope.row.securityId" @change="hxPositionHold(scope.$index, form.listedPositionHoldList, scope.row.securityId)">
                <el-option
                  v-for="dict in securityOptions"
                  :key="dict.id"
                  :label="dict.securityLabel"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资主体')" align="center" show-overflow-tooltip min-width="160">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('投资主体') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedPositionHoldList.' + scope.$index + '.investorName'" :rules="listedPositionHoldListRules.investorName">
              <el-input v-model="scope.row.investorName" disabled :placeholder="$t('投资主体')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('持仓股数(万股)')" align="center" show-overflow-tooltip min-width="120">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('持仓股数(万股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedPositionHoldList.' + scope.$index + '.positionShare'" :rules="listedPositionHoldListRules.positionShare">
              <Money v-model="scope.row.positionShare" :placeholder="$t('持仓股数(万股)')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('持仓均价(元/股)')" align="center" min-width="140">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('持仓均价(元/股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedPositionHoldList.' + scope.$index + '.positionPrice'" :rules="listedPositionHoldListRules.positionPrice">
              <Money v-model="scope.row.positionPrice" :placeholder="$t('持仓均价(元/股)')" disabled />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资成本') + $t('金额单位')" show-overflow-tooltip min-width="120">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('投资成本') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedPositionHoldList.' + scope.$index + '.investPrincipal'" :rules="listedPositionHoldListRules.investPrincipal">
              <Money v-model="scope.row.investPrincipal" unit="w" :placeholder="$t('投资成本') + $t('金额单位')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['listed:base:remove']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addListedPositionHold">{{ $t('添加') }}</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="quickAddListedPositionHold">{{ $t('快速添加证券账户') }}</el-button>
      </div>
      <!--禁售明细-->
      <div class="area-header" style="margin-top: 15px">
        <span class="area-header-title">{{ $t('禁售明细') }}</span>
      </div>
      <el-table :data="form.listedReleaseList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('证券账号')" align="center" show-overflow-tooltip min-width="280">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('证券账号') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedReleaseList.' + scope.$index + '.securityId'" :rules="listedReleaseListRules.securityId">
              <el-select v-model="scope.row.securityId" @change="hxRelease(scope.$index, form.listedReleaseList, scope.row.securityId)">
                <el-option
                  v-for="dict in securityOptions"
                  :key="dict.id"
                  :label="dict.securityLabel"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资主体')" align="center">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('投资主体') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedReleaseList.' + scope.$index + '.investorName'" :rules="listedReleaseListRules.investorName">
              <el-input v-model="scope.row.investorName" disabled :placeholder="$t('投资主体')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('解禁股数(万股)')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('解禁股数(万股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedReleaseList.' + scope.$index + '.releaseShare'" :rules="listedReleaseListRules.releaseShare">
              <Money v-model="scope.row.releaseShare" :placeholder="$t('解禁股数(万股)')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('解禁日期')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('解禁日期') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'listedReleaseList.' + scope.$index + '.releaseDate'" :rules="listedReleaseListRules.releaseDate">
              <DatePicker v-model="scope.row.releaseDate" :placeholder="$t('解禁日期')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['listed:base:remove']" type="text" icon="el-icon-delete" @click="delListedReleaseHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addListedReleaseList">{{ $t('添加') }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" data-type="listed_deal" :btn-show="!fileBtnHide" :business-id="form.dealId" />
    </el-form>
    <div slot="footer" class="dialog-footer">
      <!--保存 取消按钮-->
      <SaveBtn has-permi="listed:base" :cancel-show="listedId === ''" />
    </div>

    <!-- 查看证券账户列表 -->
    <el-dialog
      :title="$t('证券账户')"
      :visible.sync="listOpen"
      custom-class="homeForm"
      width="70%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <searchListedSecurityList ref="searchListedSecurityList" />
    </el-dialog>

    <!-- 快速添加上市项目-证券账户管理对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <listedSecurityForm ref="listedSecurityForm" />
    </el-dialog>
  </div>
</template>

<script>
import {
  saveListedDeal,
  getListedDeal,
  findByDealIdAndSecurityId,
  getClosePrice, getByDealId
} from '@/api/deal/listed/base/listedDeal'
import DealSelect from '@/components/Select/dealSelect'
import searchListedSecurityList from '@/views/deal/listed/base/searchListedSecurityList'
import listedSecurityForm from '@/views/deal/listed/security/listedSecurityForm'
import { delListedPositionHold } from '@/api/deal/listed/position/listedPositionHold'
import { delListedRelease } from '@/api/deal/listed/release/listedRelease'
import { listListedSecurity } from '@/api/deal/listed/security/listedSecurity'

export default {
  components: {
    DealSelect,
    searchListedSecurityList,
    listedSecurityForm
  },
  props: {
    listedId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      // 表单参数
      form: {
        listedPositionHoldList: [],
        listedReleaseList: [],
        fileList: []
      },
      // 遮罩层
      loading: false,
      listOpen: false,
      formOpen: false,
      investorId: undefined,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 文件上传按钮是否隐藏其它按钮
      fileBtnHide: true,
      securityOptions: [],
      yesNoOptions: [],
      currentPage: undefined,
      title: '',
      // 查询股票详情返回的信息
      message: '',
      // 查询股票详情返回的设置的状态
      queryStatus: true,
      // 表单校验
      rules: {
        dealId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        market: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        stockCode: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }, { validator: this.checkMsgStatus, trigger: 'click' }],
        launchDate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        totalEquity: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        personCharge: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        whetherBod: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        bodList: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 证券账户持仓信息表单校验
      listedPositionHoldListRules: {
        securityId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        securityAccount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        securityName: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        positionShare: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        investPrincipal: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      // 项目解禁表单校验
      listedReleaseListRules: {
        securityId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        investorName: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        releaseShare: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        releaseDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      // 上市项目查询条件
      listedQueryParam: {
        listedId: ''
      }
    }
  },
  watch: {
    'form.dealId': {
      handler(val) {
        if (val !== null && val !== undefined && val !== '') {
          this.fileBtnHide = false
        } else {
          this.fileBtnHide = true
        }
      },
      deep: true,
      immediate: true
    },
    'form.totalEquity'() {
      this.calShareRate()
    },
    'form.shareHold'() {
      this.calShareRate()
      this.calMarketValue()
    },
    'form.closePrice'() {
      this.calMarketValue()
    },
    'form.listedPositionHoldList': {
      handler() {
        this.getAmountSum()
      },
      deep: true,
      immediate: true
    },
    listedId: {
      handler(val) {
        if (val != null && val !== '') {
          this.form.id = val
          this.init(this.form)
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('listed_market').then(response => {
      this.marketOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.yesNoOptions = response.data
    })
    // 获取证券账户options
    this.listedQueryParam.dealType = (this.$route.query.dealType === undefined ? 'equity' : this.$route.query.dealType)
    // 判断当前页面所在位置
    if (this.$route.query.pageType === 'spo') {
      this.listedQueryParam.dealType = this.currentPage = 'spo'
      this.initDeal()
    }
    listListedSecurity(this.listedQueryParam).then(response => {
      this.securityOptions = response.rows
    })
    if (this.listedId !== '' && this.listedId !== null && this.listedId !== undefined) {
      const queryParam = {
        id: this.listedId
      }
      this.init(queryParam)
    }
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data !== '' && data.id !== undefined) {
        getListedDeal(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    initDeal() {
      getByDealId(this.$route.query.id).then(response => {
        console.log(response)
        if (response.data !== null) {
          this.form = response.data
        } else {
          this.reset()
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        dealType: (this.$route.query.dealType === undefined ? (this.currentPage !== 'spo' ? 'equity' : 'spo') : this.$route.query.dealType),
        market: undefined,
        stockCode: undefined,
        closePrice: undefined,
        marketValue: undefined,
        launchDate: undefined,
        totalEquity: undefined,
        currCapital: undefined,
        personCharge: undefined,
        whetherBod: undefined,
        bodList: undefined,
        shareHold: undefined,
        shareRate: undefined,
        totalInvestAmount: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        listedPositionHoldList: [],
        listedReleaseList: [],
        fileList: []
      }
      this.resetForm('form')
    },
    getSecurityList() {
      listListedSecurity(this.listedQueryParam).then(response => {
        this.securityOptions = response.rows
      })
    },
    // 计算持股比例
    calShareRate() {
      if (this.form.totalEquity !== undefined && this.form.totalEquity !== null && this.form.totalEquity !== '') {
        if (this.form.shareHold !== undefined && this.form.shareHold !== null && this.form.shareHold !== '') {
          if (this.form.totalEquity !== 0) {
            this.form.shareRate = ((parseFloat(this.form.shareHold) / parseFloat(this.form.totalEquity)) * 100)
          } else {
            this.$set(this.form, 'totalEquity', '')
            this.$set(this.form, 'shareRate', 0)
          }
        }
      }
    },
    // 计算市值  公式：市值=最新收盘价*我方持有股数
    calMarketValue() {
      if (this.form.closePrice !== undefined && this.form.closePrice !== null && this.form.closePrice !== '') {
        if (this.form.shareHold !== undefined && this.form.shareHold !== null && this.form.shareHold !== '') {
          this.form.marketValue = (parseFloat(this.form.shareHold * 10000) * parseFloat(this.form.closePrice))
        }
      }
    },
    // 添加持仓信息
    addListedPositionHold() {
      if (this.form.dealId !== undefined && this.form.dealId !== '') {
        // 跟新新的证券账户信息
        this.getSecurityList()
        const row = {
          id: undefined,
          securityId: '',
          securityAccount: '',
          securityName: '',
          investorName: '',
          positionShare: '',
          positionPrice: '',
          investPrincipal: '',
          remark: ''
        }
        if (!(this.form.listedPositionHoldList instanceof Array)) {
          this.$set(this.form, 'listedPositionHoldList', [])
        }
        this.$nextTick(() => {
          this.form.listedPositionHoldList.push(row)
        })
      } else {
        return this.msgError(this.$t('请先选择项目'))
      }
    },
    // 删除持仓信息
    delHandle(index, row) {
      // eslint-disable-next-line no-undef
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delListedPositionHold(id)
          }).then(() => {
          this.form.listedPositionHoldList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.form.listedPositionHoldList.splice(index, 1)
      }
    },
    // 重置持仓信息列表中的数据
    clearPositionHoldByListIndex(list, index) {
      list[index].id = ''
      list[index].securityId = ''
      list[index].securityAccount = ''
      list[index].securityName = ''
      list[index].investorName = ''
      list[index].positionShare = ''
      list[index].positionPrice = ''
      list[index].investPrincipal = ''
      list[index].remark = ''
    },
    // 选中证券账户列表做数据回显
    hxPositionHold(index, list, securityId) {
      // 先判断是否已经选中
      for (var i = 0; i < list.length; i++) {
        if (list !== 1) {
          if (i !== index) {
            if (list[i].securityId === securityId) {
              this.clearPositionHoldByListIndex(list, index)
              return this.msgError(this.$t('该证券账户已经添加'))
            }
          }
        }
      }
      if (this.form.dealId !== null && this.form.dealId !== undefined) {
        findByDealIdAndSecurityId(this.form.dealId, securityId).then(response => {
          if (response.data != null) {
            this.form.listedPositionHoldList[index].investorName = response.data.investorName
            this.form.listedPositionHoldList[index].positionShare = response.data.numberOfShares / 10000
            this.form.listedPositionHoldList[index].investPrincipal = response.data.amountInvestmentFact
            if (response.data.numberOfShares !== '0' && response.data.numberOfShares !== null && response.data.numberOfShares !== undefined && response.data.numberOfShares !== '') {
              if (response.data.amountInvestmentFact !== '' && response.data.amountInvestmentFact !== null && response.data.amountInvestmentFact !== undefined) {
                this.form.listedPositionHoldList[index].positionPrice = response.data.amountInvestmentFact / response.data.numberOfShares / 10000
              }
            } else {
              this.form.listedPositionHoldList[index].positionPrice = ''
            }
          }
        })
      }
    },
    // 重置禁售明细列表中的数据
    clearReleaseByListIndex(list, index) {
      list[index].id = ''
      list[index].securityId = ''
      list[index].securityAccount = ''
      list[index].securityName = ''
      list[index].investorName = ''
      list[index].releaseShare = ''
      list[index].releaseDate = ''
      list[index].remark = ''
    },
    // 选中项目解禁列表做数据回显
    hxRelease(index, list, securityId) {
      // 先判断是否已经选中
      // for (var i = 0; i < list.length; i++) {
      //   if (list !== 1) {
      //     if (i !== index) {
      //       if (list[i].securityId === securityId) {
      //         this.clearReleaseByListIndex(list, index)
      //         return this.msgError(this.$t('该证券账户已经添加'))
      //       }
      //     }
      //   }
      // }
      if (this.form.dealId !== null && this.form.dealId !== undefined) {
        findByDealIdAndSecurityId(this.form.dealId, securityId).then(response => {
          if (response.data != null) {
            this.form.listedReleaseList[index].investorName = response.data.investorName
            this.form.listedReleaseList[index].releaseShare = ''
            this.form.listedReleaseList[index].releaseDate = ''
          }
        })
      }
    },
    /** 快速添加证券账户按钮 */
    quickAddListedPositionHold() {
      this.formOpen = true
      this.title = '添加证券账户'
      this.$nextTick(() => {
        this.$refs.listedSecurityForm.setSource('listedDealForm')
      })
    },
    // 获取最新收盘价
    getClosePrice(val) {
      if (val !== '' && val !== undefined && val !== null) {
        getClosePrice(val).then(response => {
          if (response.data.code === '200') {
            console.log(response.data)
            if (response.data.stockInfo.mgjzc !== '') {
              this.form.closePrice = parseFloat(response.data.stockInfo.closePrice)
              this.form.launchDate = response.data.stockInfo.listing_date
              this.form.totalEquity = response.data.stockInfo.totalcapital
              this.form.currCapital = response.data.stockInfo.currcapital
              this.message = response.data.message
              this.queryStatus = true
              this.$refs.form.validateField('stockCode')
            } else {
              this.message = response.data.message
              this.queryStatus = false
              this.$refs.form.validateField('stockCode')
            }
          } else {
            this.message = response.data.message
            this.queryStatus = false
            this.$refs.form.validateField('stockCode')
          }
        })
      }
    },
    // 我方持有股数 我方投资总金额
    getAmountSum() {
      let positionShareSum = 0
      let investPrincipalSum = 0
      if (this.form.listedPositionHoldList !== null && this.form.listedPositionHoldList !== undefined && this.form.listedPositionHoldList.length > 0) {
        this.form.listedPositionHoldList.forEach(item => {
          if (item.positionShare !== undefined && item.positionShare !== null && item.positionShare !== '') {
            positionShareSum += +item.positionShare
            if (item.investPrincipal !== undefined && item.investPrincipal !== null && item.investPrincipal !== '') {
              item.positionPrice = (item.investPrincipal / 10000) / item.positionShare
            }
          }
          if (item.investPrincipal !== undefined && item.investPrincipal !== null && item.investPrincipal !== '') {
            investPrincipalSum += +item.investPrincipal
          }
        })
        if (positionShareSum !== 0) {
          this.$set(this.form, 'shareHold', positionShareSum)
        } else {
          this.$set(this.form, 'shareHold', undefined)
        }
        if (investPrincipalSum !== 0) {
          this.$set(this.form, 'totalInvestAmount', investPrincipalSum)
        } else {
          this.$set(this.form, 'totalInvestAmount', undefined)
        }
      }
    },
    // 添加项目解禁
    addListedReleaseList() {
      if (this.form.dealId !== undefined && this.form.dealId !== '') {
        const row = {
          id: undefined,
          securityId: '',
          securityAccount: '',
          securityName: '',
          investorName: '',
          releaseShare: '',
          releaseDate: '',
          remark: ''
        }
        if (!(this.form.listedReleaseList instanceof Array)) {
          this.$set(this.form, 'listedReleaseList', [])
        }
        this.$nextTick(() => {
          this.form.listedReleaseList.push(row)
        })
      } else {
        return this.msgSuccess(this.$t('请先选择项目'))
      }
    },
    // 删除项目解禁
    delListedReleaseHandle(index, row) {
      // eslint-disable-next-line no-undef
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delListedRelease(id)
          }).then(() => {
          this.form.listedReleaseList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.form.listedReleaseList.splice(index, 1)
      }
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveListedDeal(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 校验查询股票详情查询的状态提示
    checkMsgStatus(rule, value, callback) {
      if (this.queryStatus) {
        callback()
      } else {
        callback(new Error(this.$t(this.message)))
      }
    }

  }

}
</script>
